package com.ciwong.epaper.modules.exam;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.ciwong.ciwongwrite.JournalActivity;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.H5AnswersResponse;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperAction;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.interactivetutorial.InteractiveTutorialCordovaActivity;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerPhotoBean;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerSubMitResultBean;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.ui.NewLoginActivity;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.DeviceUtil;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpHelper;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseSystem;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created by albus on 2017/7/10.
 */

public class ExamActivity extends BaseActivity implements SystemWebViewClient.LoadCallback, View.OnClickListener {
    private static final int TAKE_PHOTOFORPAD = 4;
    /**
     * 唯一标识符
     */
    protected String uuid = UUID.randomUUID().toString();
    //    private static final String TEMP_CAMERA_FILE = ESystem.getImagesPath(ExamActivity.this) + File.separator + BaseSystem.PROJECT_FOLDER + "temp.jpg";
    private String callbackId;
    private String answerJson;
    private int contentId;
    private long effctivTime;
    /**
     * 1:作业进来，2：书桌进来
     */
    private int OnlineAnswerFrom = FROM_HOME_WORK;
    public static final int FROM_HOME_WORK = 1;
    public static final int FROM_DESK = 2;
    /**
     * 网页展示内容
     */
    private String result;
    private String versionId;
    private String classId;
    private String workId = "0";
    private UserInfoBase userInfo;
    private Answer tempAnswer;
    private Gson gson = new Gson();
    private WorkContents workContent;
    private H5AnswersResponse h5AnswersResponse;
    private DownLoadInfo mDownLoadInfo;
    private long startTime;
    private long returnWorkLong;

    @Override
    protected void onStart() {
        isJumpToResult = true;
        super.onStart();
    }

    @Override
    protected int setView() {
        return R.layout.activity_online_answer_cordova;
    }

    protected SystemWebView systemWebView;
    protected CordovaWebView cordovaWebView;
    /**
     * 提交中的界面
     */
    LinearLayout ll_submiting;
    RelativeLayout rel_submit_fail;
    Button brn_submit_again;

    @Override
    protected void findViews() {

        ll_submiting = (LinearLayout) findViewById(R.id.ll_submiting);
        systemWebView = (SystemWebView) findViewById(R.id.system_webview);
        systemWebView.getSettings().setBuiltInZoomControls(false);
        systemWebView.getSettings().setSavePassword(false);
        //android 11 上面google出于安全考虑，不推荐用webview直接访问文件，如果实际项目中有需要，就需要设置为true
        systemWebView.getSettings().setAllowFileAccess(true);
        brn_submit_again = (Button) findViewById(R.id.btn_submit_again);
        rel_submit_fail = (RelativeLayout) findViewById(R.id.rel_submit_fail);
    }

    @Override
    protected void init() {
        Intent intent = getIntent();

        SystemWebViewEngine systemWebViewEngine = new SystemWebViewEngine(systemWebView);
        cordovaWebView = new CordovaWebViewImpl(systemWebViewEngine);
        ConfigXmlParser configXmlParser = new ConfigXmlParser();
        configXmlParser.parse(this);
        cordovaWebView.init(this, cordovaInterface, configXmlParser.getPluginEntries(), configXmlParser.getPreferences());
        SystemWebChromeClient systemWebChromeClient = new SystemWebChromeClient(systemWebViewEngine) {
            @Override
            public void onReceivedTitle(WebView view, String title) {//监听标题改变
                setTitleText(title);
                showBackBar();
            }
        };
        systemWebView.setWebChromeClient(systemWebChromeClient);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            systemWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        handler.postDelayed(runnable, 1000);//每一秒执行一次runnable,作业耗时加一秒.
        workContent = (WorkContents) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENT);
        effctivTime = intent.getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, 0);
        contentId = workContent.getContentId();
        versionId = workContent.getVersionId();
        OnlineAnswerFrom = intent.getIntExtra(IntentFlag.INTENT_FLAG_H5_PAGE_TYPE_SOURCE, -1);
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        //构造一个DownLoadInfo 用于传递 chapterid
        mDownLoadInfo = new DownLoadInfo();
        mDownLoadInfo.setChapterId(workContent.getcId());
        setValideSource(false);
        startTime = CWSys.getSharedLong(getStartTimeKey(), 0);
        if (startTime == 0) {
            if (null != workContent) {
                startTime = workContent.getStartTime();
                CWSys.setSharedLong(getStartTimeKey(), startTime);
            }
        }

        String onLineAnswerKey = getOnLineAnswerKey();
        int saveTotalTime = CWSys.getSharedInt(onLineAnswerKey, -1);
        if (saveTotalTime != -1) {
            totalTime = saveTotalTime;
        }
    }


    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    @Override
    protected void loadData() {
        showH5View();
        // TODO: 2018/8/27 lzh
        if (DeviceUtil.isPad()) {
//            start_url = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paper.html?client=22222";
            start_url = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paper.html";
        } else {
            start_url = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paper.html";
        }
        cordovaWebView.loadUrl(start_url);
        showBackBar();
        checkSubmitFailAnswer();
        checkUnUpLoadPhotos();
    }


    @Override
    protected void initEvent() {
        EventBus.getDefault().register(this);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                onBackPressed();
            }
        });
        brn_submit_again.setOnClickListener(this);
        ALiYunManager.getInstance().registerListener(aLiYunListener);
    }

    public void onEventMainThread(SubmitEvent submitEvent) {
        final String id = submitEvent.getId();
        final String callbackId = submitEvent.getCallbackId();
        if (id.equals("SetTitle")) {
//            setTitle(submitEvent); //标题栏已经由H5提供，app端不用再显示标题
        } else if ("Submit".equals(id)) {
//            提交作业(submitEvent);
        } else if (id.equals("GetOnlineExamination")) {//获取题目内容
//            getOnlineExamination(callbackId);
            getExamExamination(callbackId);

        } else if (id.equals("GetOnlineAnswer")) {//获取用户答案
            getOnlineAnswer(callbackId);
        } else if (id.equals("SetOnlineAnswer")) {//保存答案到本地
            setOnlineAnswer(submitEvent.getJson());
        } else if (id.equals("SubmitOnlineAnswer")) {//提交答案到服务器
            String answerJson = submitEvent.getJson();
            submitOnlineAnswer(callbackId, answerJson);
        } else if (id.equals("ExitOnlineAnswer")) {//退出作答界面
            exitOnlineAnswer(submitEvent.getJson());
        } else if (id.equals("GetOnlineKey")) {//
            getOnlineKey(callbackId);
        } else if (id.equals("TakePhoto")) {
            TakePhoto(submitEvent);
        } else if (id.equals("TakePhotoForPad")) {
            TakePhotoForPad(submitEvent);
        }
    }


    private void getExamExamination(final String callbackId) {

        Response.Listener listener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
//                CWLog.i("onresponse", response.toString());
                if (!TextUtils.isEmpty(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.has("data")) {
                            Object obj = jsonObject.get("data");
                            JSONObject jsonObject1 = new JSONObject(obj.toString());
                            if (OnlineAnswerFrom == 1) {//来自作业
                                jsonObject1.put("isWork", 1);
                            } else {
                                jsonObject1.put("isWork", 2);//来自书桌
                            }
                            result = jsonObject1.toString();
                            sendCallBackSuccess(callbackId, result);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                CWLog.i("onresponse", volleyError.toString());
            }
        };
        Map<String, String> params = new HashMap<>();
        params.put("clientId", EConstants.CLIENT_ID);
        BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
        params.put("accessToken", verifyInfo.getAccessToken());
        params.put("brandId", EApplication.BRAND_ID + "");
        params.put("versionId", versionId + "");
        String url = HttpHelper.concatUrl(params, EpaperAction.ACTION_GETEXAM_EXAMINATION + "?");
        StringRequest request = new StringRequest(url, listener, errorListener);
        RequestQueue mQueue = Volley.newRequestQueue(this);
        mQueue.add(request);
    }

    public static final int PHOTO_REQUEST_CAMERA = 3;
    /**
     * 图片保存地址
     */
    private String mCameraPath;
    private static final int REQUEST_PERMISSION_CAMERA = 1;

    private void TakePhotoForPad(SubmitEvent submitEvent) {
        try {
            String photoName = new JSONObject(submitEvent.getJson()).getString("fileName");
            mCameraPath = ESystem.getAnswersImagesPath("OnlineAnswerPic") + File.separator + photoName + ".png";
            callbackId = submitEvent.getCallbackId();
            Intent takePhotoForPadIntent = new Intent(this, JournalActivity.class);
            takePhotoForPadIntent.putExtra(JournalActivity.PHOTOPATH, mCameraPath);
            startActivityForResult(takePhotoForPadIntent, TAKE_PHOTOFORPAD);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void TakePhoto(SubmitEvent submitEvent) {
        try {
            String photoName = new JSONObject(submitEvent.getJson()).getString("fileName");
            mCameraPath = ESystem.getAnswersImagesPath("OnlineAnswerPic") + File.separator + photoName + EConstants.CAMERA_DEFAULT_SUFFIX;
            callbackId = submitEvent.getCallbackId();
            boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
            if (isHavePermiss) {
                String tempCameraFile = ESystem.getImagesPath(ExamActivity.this) + File.separator + BaseSystem.PROJECT_FOLDER + "temp.jpg";
                //有权限
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                Uri fileUri = FileProvider7.getUriForFile(this, new File(tempCameraFile));
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
            } else {
                //无权限
                showgetCameraPermissDialog();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
        if (isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(this);
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        List<String> permissionList_camera = new ArrayList<String>();
        Map<String, String> noteMap_camera = new HashMap<>();
        noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
        permissionList_camera.add(Manifest.permission.CAMERA);
        if (Build.VERSION.SDK_INT >= 30) {
            permissionList_camera.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap_camera.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
        }
        XXPermissionTool.checkPermissions(this, //
                permissionList_camera, //
                noteMap_camera, //
                REQUEST_PERMISSION_CAMERA, //
                new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                    @Override
                    public void onCheckPermissionsFinished(int flag) {
                        if (0 == flag) {
                            String tempCameraFile = ESystem.getImagesPath(ExamActivity.this) + File.separator + BaseSystem.PROJECT_FOLDER + "temp.jpg";
                            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri fileUri = FileProvider7.getUriForFile(ExamActivity.this, new File(tempCameraFile));
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            cameraIntent.putExtra("return-data", true);
                            startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
                        }
                    }
                });
    }

    public void onEventMainThread(Answer answer) {
        CWLog.i("作业上传进度", answer.getProgress() + "提交状态" + answer.submitStatus);
    }

    public String getStartTimeKey() {
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        String userId = "";
        if (null != userInfo) {
            userId = userInfo.getUserId() + "";
        }
        String key = versionId + workId + OnlineAnswerFrom + userId + EApplication.BRAND_ID + SerializableManager.SerializeKey.SHARE_KET_WORK_NOW_DATA;
        return key;
    }

    public String getOnLineAnswerKey() {

        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        String userId = "";
        if (null != userInfo) {
            userId = userInfo.getUserId() + "";
        }
        String key = versionId + workId + OnlineAnswerFrom + userId + EApplication.BRAND_ID;
        return key;
    }

    /**
     * 是否有主观题
     */
    private boolean isSubjective = false;

    /**
     * 提交作业
     *
     * @param callbackId
     * @param answerJson
     */
    private void submitOnlineAnswer(final String callbackId, String answerJson) {
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return;
        }
        try {
            h5AnswersResponse = gson.fromJson(answerJson, H5AnswersResponse.class);
            int remainNum = Integer.parseInt(h5AnswersResponse.remainNum);
            if (remainNum > 0) {
                String tips = "您还有" + remainNum + "道题目未完成，确定交卷吗？";
                showConfirmCommitDialog(this, tips, callbackId, answerJson);
            } else {
                submitAnswer(callbackId, answerJson);

            }
        } catch (Exception e) {
            submitAnswer(callbackId, answerJson);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_CAMERA:
//                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//
//                }
                break;

            default:
                break;
        }
    }

    private Handler upLoadPicHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String callbackId = bundle.getString("callbackId");
            String answerJson = bundle.getString("answerJson");
            submitAnswer(callbackId, answerJson);
        }
    };
    private CWDialog loginOut_cwDialog;
    private boolean isSubmiting = false;

    private void submitAnswer(final String callbackId, final String answerJson) {
        showSubmitView();
        for (OnlineAnswerPhotoBean onlineAnswerPhotoBean : onlineAnswerPhotoBeans) {
            if (TextUtils.isEmpty(onlineAnswerPhotoBean.photoUrl)) { //没有url说明上传还未完成
                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("callbackId", callbackId);
                bundle.putString("answerJson", answerJson);
                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                message.setData(bundle);
                upLoadPicHandler.sendMessageDelayed(message, 2000);
                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                return;
            }
        }
        final Answer answer = getAnswer(answerJson);
        String submitWorkJson = gson.toJson(answer);

        EpaperDao.getInstance().submitWork(submitWorkJson, 0, answer, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
//                showToastError("答案提交失败，请重试");
                CWLog.i("答案提交失败errorCode:" + errorCode, data.toString());
                if (errorCode == 17) { //登录异常
                    if (loginOut_cwDialog == null) {
                        loginOut_cwDialog = new CWDialog(ExamActivity.this);
                    }
                    String mUserId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy年MM月dd日");
                    loginOut_cwDialog.setMessage("你的账号(" + mUserId + ")于" + sd.format(new Date()) + "在另外一台设备登录。如非本人操作，则密码可能已经泄露，建议及时修改密码。");
                    loginOut_cwDialog.setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MeJumpManager.jumpToLogin2(ExamActivity.this, R.string.go_back, null, null, EConstants.LoginFrom.LOGIN_FROM_SUBMIT_WORK);
                            loginOut_cwDialog.dismiss();
                        }
                    });
                    loginOut_cwDialog.show();
                }
                showSubmitFailView();
                SerializableManager.getInstance().serialize(getOnLineAnswerKey(), answerJson);
                ESystem.setSharedString(getOnLineAnswerKey(), callbackId);
                sendCallBackSuccess(callbackId, 0);

            }

            @Override
            public void failed(Object data) {
                SerializableManager.getInstance().serialize(getOnLineAnswerKey(), answerJson);
                ESystem.setSharedString(getOnLineAnswerKey(), callbackId);
                CWLog.i("答案提交失败", data.toString());
                showSubmitFailView();
                sendCallBackSuccess(callbackId, 0);
            }

            @Override
            public void success(Object data) {

                OnlineAnswerSubMitResultBean onlineAnswerSubMitResultBean = (OnlineAnswerSubMitResultBean) data;
                isSubjective = onlineAnswerSubMitResultBean.isHasNoCorrect();
                returnWorkLong = onlineAnswerSubMitResultBean.getWorkLong();
                answer.actualScore = onlineAnswerSubMitResultBean.getScore();
                sendCallBackSuccess(callbackId, 1);
                SerializableManager.getInstance().serialize(getOnLineAnswerKey(), "");
                //表示该次作业做完，下次计时从零开始计
                CWSys.setSharedLong(getStartTimeKey(), 0);
                String onLineAnswerKey = getOnLineAnswerKey();
                CWSys.setSharedInt(onLineAnswerKey, -1);
                ESystem.setSharedString(getOnLineAnswerKey(), "");
                if (isJumpToResult) { //如果当前activity还在前台就跳转。
                    DownLoadInfo downLoadInfo = new DownLoadInfo();
                    downLoadInfo.setBookId(workContent.getPackageId());
                    downLoadInfo.setChapterId(workContent.getcId());
                    downLoadInfo.setResourceName(workContent.getResourceName());
                    downLoadInfo.setVersionId(workContent.getVersionId());
                    MeJumpManager.jumpToOnlineAnswerResultActivity(ExamActivity.this, OnlineAnswerFrom, totalTime, onlineAnswerSubMitResultBean.getDoWorkId(), answer.workScore, onlineAnswerSubMitResultBean.getScore(), isSubjective, contentId + "", downLoadInfo, 0, effctivTime, workContent, returnWorkLong);
                    finish();
                }
                isSubmiting = false;
            }
        });
    }

    private boolean isJumpToResult = true;

    private void checkSubmitFailAnswer() {
        SerializableManager.getInstance().deSerialize(getOnLineAnswerKey(), new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    ExamActivity.this.answerJson = String.valueOf(data);
                    callbackId = ESystem.getSharedString(getOnLineAnswerKey());
                    if (!TextUtils.isEmpty(answerJson) && !TextUtils.isEmpty(callbackId)) {
                        showSubmitFailView();
                    }
                }
            }
        });
    }

    private List<OnlineAnswerPhotoBean> onlineAnswerPhotoBeans = new ArrayList<OnlineAnswerPhotoBean>();

    private void exitOnlineAnswer(String answerJson) {
        String onLineAnswerKey = getOnLineAnswerKey();
        String onLineAnswerPhotoKye = getOnLineAnswerPhotoKye();
        DialogUtil.showConfirmEndOnlineAnswerDialog(ExamActivity.this, answerJson, onLineAnswerKey, isSubmiting, onLineAnswerPhotoKye, onlineAnswerPhotoBeans, onLineAnswerKey, totalTime);
    }

    /**
     * 检查未上传成功的图片
     */
    private void checkUnUpLoadPhotos() {
        String onLineAnswerPhotoKye = getOnLineAnswerPhotoKye();
        SerializableManager.getInstance().deSerialize(onLineAnswerPhotoKye, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    List<OnlineAnswerPhotoBean> unUpLoadPhotos = (List<OnlineAnswerPhotoBean>) data;
                    Iterator<OnlineAnswerPhotoBean> iterator = unUpLoadPhotos.iterator();
                    if (iterator.hasNext()) {
                        OnlineAnswerPhotoBean onlineAnswerPhotoBean = iterator.next();
                        if (new File(onlineAnswerPhotoBean.photoPath).exists()) {
                            ALiYunManager.getInstance().add(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                        } else {
                            unUpLoadPhotos.remove(onlineAnswerPhotoBean);
                        }
                    }
                    onlineAnswerPhotoBeans.addAll(unUpLoadPhotos);
                    SerializableManager.getInstance().serialize(getOnLineAnswerPhotoKye(), null);
                }
                super.success(data);
            }
        });
    }

    private String getOnLineAnswerPhotoKye() {
        return getOnLineAnswerKey() + "photo";
    }

    private Answer getAnswer(String H5SendanswerJson) {
        tempAnswer = new Answer();
        tempAnswer.setContentId(contentId);
        tempAnswer.setDoWorkPackageUrl("");
        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        userInfo = application.getUserInfoBase();
        if (null != userInfo && null != H5SendanswerJson) {
            if (TextUtils.isEmpty(workId)) {
                workId = "0";
            }
            tempAnswer.setWorkId(workId);
            tempAnswer.setWorkLong(totalTime);
            tempAnswer.setStartTime(startTime);
            if (clazz == null) {
                classId = "0";
            } else {
                classId = clazz.getClassId() + "";
            }
            tempAnswer.setClassId(classId);
            tempAnswer.setUserName(userInfo.getRealName());
            tempAnswer.remainNum = h5AnswersResponse.remainNum;

            try {
                JSONObject jsonObject = new JSONObject(H5SendanswerJson);

                tempAnswer.setWorkAnswers(jsonObject.getString("answers"));
                JSONObject resultJsonObject = new JSONObject(result);
                String ref_score = resultJsonObject.getString("ref_score");

                tempAnswer.setWorkScore(Float.parseFloat(ref_score));
            } catch (JSONException e) {
                tempAnswer.setWorkAnswers("[]");
            }
//            tempAnswer.setActualScore(h5AnswersResponse.totalScore);
            tempAnswer.setJsonVersion(EConstants.JSON_VERSION);
            tempAnswer.setUserAnswer(ESystem.USER_ANSWER);
            tempAnswer.setCreateTime(System.currentTimeMillis());
            tempAnswer.setBrandId(EApplication.BRAND_ID);
            tempAnswer.setResourceName(workContent.getResourceName());
            tempAnswer.setVersionId(versionId);
            tempAnswer.setParentVersionId("0");
            tempAnswer.setModuleId(workContent.getModuleId());
            tempAnswer.setResourceType("1f693f76-02f5-4a40-861d-a8503df5183f");
//            }
            tempAnswer.setPackageId("0");
            tempAnswer.setcId("0");
//            }

        }
        return tempAnswer;
    }

    /**
     * 设置用户已经作答的答案
     */
    private void setOnlineAnswer(String answer) {

        SerializableManager.getInstance().serialize(getOnLineAnswerKey(), answer);
    }

    private void getOnlineAnswer(final String callbackId) {
        SerializableManager.getInstance().deSerialize(getOnLineAnswerKey(), new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                sendCallBackSuccess(callbackId, "");
            }

            @Override
            public void failed(Object data) {
                sendCallBackSuccess(callbackId, "");
            }

            @Override
            public void success(Object data) {
                sendCallBackSuccess(callbackId, data.toString());
            }
        });
    }

    private void getOnlineKey(String callbackId) {
        String onLineAnswerKey = getOnLineAnswerKey();
        sendCallBackSuccess(callbackId, onLineAnswerKey);
    }

    public String start_url = "http://192.168.18.181/mobile/v1706_moliban/onlinePaper/index.html";
    /**
     * 做作业耗时
     */
    private int totalTime = 0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            totalTime++;
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    public void onLoadOver() {
        hideTitleBar();
    }

    @Override
    public void onBackFinish() {

    }

    @SuppressLint("NewApi")
    @Override
    public void onBackPressed() {
        try {
            systemWebView.evaluateJavascript("local.getAnswer()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String answer) {
                    CWLog.i("从JS获取的答案：", answer);
                    exitOnlineAnswer(answer);
                }
            });

        } catch (NoSuchMethodError error) {
        }
    }


    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    protected CordovaInterfaceImpl cordovaInterface = new CordovaInterfaceImpl(this) {
        @Override
        public Object onMessage(String id, Object data) {
            if ("onPageFinished".equals(id)) {
                try {

                    onPageFinishedUrl.add((String) data);

                } catch (IllegalStateException e) {

                }
            }
            return super.onMessage(id, data);
        }
    };


    private void showH5View() {
        isSubmiting = false;
        systemWebView.setVisibility(View.VISIBLE);
        hideTitleBar();
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.GONE);
    }

    private void showSubmitView() {
        isSubmiting = true;
        showTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.VISIBLE);
        rel_submit_fail.setVisibility(View.GONE);
    }

    private void showSubmitFailView() {
        isSubmiting = true;
        hideTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.VISIBLE);
    }

    private void sendCallBackSuccess(String callbackId, JSONObject result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    private void sendCallBackFail(String callbackId, String error) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.error(error);
    }

    private void sendCallBackSuccess(String callbackId, String result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    private void sendCallBackSuccess(String callbackId, int result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    public CordovaWebView getCordovaWebView() {
        return cordovaWebView;
    }

    @Override
    protected void onDestroy() {
        isJumpToResult = false;
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
        EventBus.getDefault().unregister(this);

        if (systemWebView != null)
            systemWebView.destroy();
        if (cordovaWebView != null)
            cordovaWebView.getEngine().destroy();
        if (cordovaWebView != null)
            cordovaWebView.getPluginManager().onDestroy();
        super.onDestroy();
    }


    @Override
    public void finish() {
        isJumpToResult = false;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ViewGroup view = (ViewGroup) getWindow().getDecorView();
                view.setBackgroundColor(getResources().getColor(R.color.white));
                for (int i = 0; i < view.getChildCount(); i++) {
                    if (view.getChildAt(i).getParent() != null) {
                        view.removeView(view.getChildAt(i));
                    }
                }
                ExamActivity.super.finish();
            }
        });
    }

    /**
     * 未完成作业提交提醒窗口
     */
    public void showConfirmCommitDialog(final Activity context, final String tips, final String callbackId, final String answerJson) {
        CWDialog dialog = new CWDialog(context);
        dialog.setMessage(tips);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                submitAnswer(callbackId, answerJson);

                            }
                        })
                .show();
    }

    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            try {
                OnlineAnswerPhotoBean onlineAnswerPhotoBean = (OnlineAnswerPhotoBean) tag;
                for (OnlineAnswerPhotoBean answerPhotoBean : onlineAnswerPhotoBeans) {
                    if (answerPhotoBean.photoPath.equals(onlineAnswerPhotoBean.photoPath)) {
                        answerPhotoBean.photoUrl = url;
                    }
                }
            } catch (Exception e) {
                showToastError("图片上传失败，请重试");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
//                OnlineAnswerPhotoBean onlineAnswerPhotoBean = (OnlineAnswerPhotoBean) tag;
//                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
            }
        }
    };

    @Override
    protected void onResume() {
        isJumpToResult = true;
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_submit_again) {//重新提交
            if (!NetworkUtils.isOnline()) {
                ToastUtil.INSTANCE.toastCenterNoNetError();
                return;
            }
            submitAnswer(callbackId, answerJson);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == NewLoginActivity.FOR_LOGIN) {//顶号后重新登录成功
                finish();

            } else if (requestCode == PHOTO_REQUEST_CAMERA) {
                try {
                    String tempCameraFile = ESystem.getImagesPath(ExamActivity.this) + File.separator + BaseSystem.PROJECT_FOLDER + "temp.jpg";
                    String outputPath = FileUtil.compressImage(tempCameraFile, mCameraPath, 100);
                    OnlineAnswerPhotoBean onlineAnswerPhotoBean = new OnlineAnswerPhotoBean();
                    onlineAnswerPhotoBean.photoPath = outputPath;
                    onlineAnswerPhotoBean.callbackId = callbackId;
                    ALiYunManager.getInstance().addPic(outputPath, onlineAnswerPhotoBean);
                    String photoUrlKey = ALiYunManager.getInstance().getPicKey(outputPath);
                    String photoUrl = ALiYunManager.ACCESS_URL + photoUrlKey;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("photoPath", outputPath);
                    jsonObject.put("photoUrl", photoUrl);
                    onlineAnswerPhotoBeans.add(onlineAnswerPhotoBean);
                    sendCallBackSuccess(onlineAnswerPhotoBean.callbackId, jsonObject);
                } catch (Exception e) {
                    showToastError("获取图片失败，请重新拍照上传");
                    e.printStackTrace();
                }
            } else if (requestCode == TAKE_PHOTOFORPAD) {
                try {
                    OnlineAnswerPhotoBean onlineAnswerPhotoBean = new OnlineAnswerPhotoBean();
                    String photoUrlKey = ALiYunManager.getInstance().getPicKey(mCameraPath);
                    String photoUrl = ALiYunManager.ACCESS_URL + photoUrlKey;
                    onlineAnswerPhotoBean.photoPath = mCameraPath;
                    onlineAnswerPhotoBean.callbackId = callbackId;
                    ALiYunManager.getInstance().addPic(mCameraPath, onlineAnswerPhotoBean);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("photoPath", mCameraPath);
                    jsonObject.put("photoUrl", photoUrl);
                    onlineAnswerPhotoBeans.add(onlineAnswerPhotoBean);
                    sendCallBackSuccess(onlineAnswerPhotoBean.callbackId, jsonObject);
                } catch (Exception e) {
                    showToastError("获取图片失败，请重新拍照上传");
                    e.printStackTrace();
                }
            }
        }

    }
}
